﻿'use strict';

angular.module('ishaCrmApp')

    .factory('stateSvc', ['$rootScope', '$cookieStore', 'growl', 'googleAuthSvc', function ($rootScope, $cookieStore, growl, googleAuthSvc) {

        var stateSvcObject = {};

        // Menu state Interface
        stateSvcObject.activeMenu = 'Home';
        stateSvcObject.setActiveMenu = function (menu) {
            this.activeMenu = menu;
            $rootScope.$emit('EVENT:MENU.CHANGED', menu);
        }

        // User Auth info interface
        stateSvcObject.authUserInfo = null;

        stateSvcObject.setAuthInfo = function (authInfo) {
            this.authUserInfo = authInfo;
            if (this.isAuthenticated()) {
                $cookieStore.put(app.CLIENT_ID, app.CookieValue);
            }
            $rootScope.$emit('EVENT:AUTH.LOGGEDIN');
        }

        stateSvcObject.loginUserEmail = function () {
            var email = $.trim(this.authUserInfo && this.authUserInfo.email ? this.authUserInfo.email : '');
            return email.toLowerCase();
        },

        stateSvcObject.loginUserFullname = function () {
            var fullname = $.trim((this.authUserInfo && this.authUserInfo.given_name ? this.authUserInfo.given_name : '') + ' ' + (this.authUserInfo && this.authUserInfo.family_name ? this.authUserInfo.family_name : ''));
            if ($.trim(fullname) == '')
                fullname = this.loginUserEmail();
            return fullname;
        }

        stateSvcObject.isAuthenticated = function () {
            var email = this.loginUserEmail();
            return (email != '');
        };

        stateSvcObject.isAuthorised = function () {

            var email = this.loginUserEmail();

            // Get List of users
            gapi.client.user.userApi.getAll().execute(function (resp) {
                if (resp && resp.statusCode) {
                    if (resp.statusCode === "SUCCESS") {
                        angular.forEach(resp.object, function (value, key) {
                            if (value.email.toLowerCase() == email) {
                                return true;
                            }
                        });
                    } else {
                        if (resp && resp.userFriendlyMessage) {
                            growl.addErrorMessage(resp.userFriendlyMessage);
                        }
                        return false;
                    }
                }
            });
        }

        stateSvcObject.login = function () {

            googleAuthSvc.login().then(function (tokenInfo) {
                // Check for access token
                if (tokenInfo && tokenInfo.access_token) {

                    // Get User profile information
                    googleAuthSvc.userInfo().then(function (profileData) {
                        if (profileData && profileData.email) {
                            stateSvcObject.setAuthInfo(profileData);
                            console.log(stateSvcObject.authUserInfo);
                        } else {
                            growl.addErrorMessage('ERROR-FETCHING-USER-PROFILE-DATA');
                        }
                    },
                    function (err) {
                        if (err) {
                            growl.addErrorMessage(err);
                        }
                        stateSvcObject.setAuthInfo(null);
                    });
                }
            }, function (err) {
                if (err) {
                    growl.addErrorMessage(err);
                }
                stateSvcObject.setAuthInfo(null);
            });
        }

        stateSvcObject.signIn = function () {

            googleAuthSvc.checkLogin().then(function (tokenInfo) {
                if (tokenInfo && tokenInfo.access_token) {
                    googleAuthSvc.userInfo().then(function (profileData) {
                        if (profileData && profileData.email) {
                            stateSvcObject.setAuthInfo(profileData);
                            console.log(profileData);
                        } else {
                            growl.addErrorMessage('ERROR-FETCHING-USER-PROFILE-DATA');
                        }
                    },
                    function (err) {
                        if (err) {
                            grow.addErrorMessage(err);
                        }
                        stateSvcObject.setAuthInfo(null);
                    });
                }
            }, function (err) {
                if (err) {
                    growl.addErrorMessage(err);
                }
                stateSvcObject.setAuthInfo(null);
            });

        },

        stateSvcObject.signOut = function () {
            this.setAuthInfo(null);
            gapi.auth.setToken(null);
            $cookieStore.remove(app.CLIENT_ID);
        }

        return stateSvcObject;

    }]);